<script setup>
import {onMounted, ref} from "vue";
import {overview} from "../../../http/rabbitmq/common.js";
import * as echarts from "echarts";
import moment from "moment";
import {listNode, listNodeName} from "../../../http/rabbitmq/node.js";
import {onBeforeRouteLeave} from "vue-router";
import {rabbitmqStore} from "../../../stores/counter.js";
import byteTools from "../../../tools/ByteTools.js";

let queueTotalMessageChartInstance = null
let queueTotalMessageStatsChartInstance = null
const overviewInfo = ref({})

const messagesStatsPublishDetails = ref([])
const messagesStatsAckDetails = ref([])
const messagesStatsConfirmDetails = ref([])

const messagesDetails = ref([])
const messagesReadyDetails = ref([])
const messagesUnacknowledgedDetails = ref([])

const nodeNameList = ref([])

function handleOverview() {
  overview().then(response => {
    overviewInfo.value = response

    messagesDetails.value = response.queue_totals.messages_details.samples.reverse()
    messagesReadyDetails.value = response.queue_totals.messages_ready_details.samples.reverse()
    messagesUnacknowledgedDetails.value = response.queue_totals.messages_unacknowledged_details.samples.reverse()

    initQueueTotalMessage(messagesDetails.value, messagesReadyDetails.value, messagesUnacknowledgedDetails.value)

    if(response.message_stats.publish_details !== undefined) {
      messagesStatsPublishDetails.value = []
      let samples = response.message_stats.publish_details.samples.reverse()
      for (let i = 0; i < (samples.length - 1); i++) {
        let item = samples[i]
        let nextItem = samples[i + 1]
        let obj = {
          "sample" : parseInt(nextItem.sample) - parseInt(item.sample),
          "timestamp" : item.timestamp,
        }
        messagesStatsPublishDetails.value.push(obj)
      }
    }

    if(response.message_stats.ack_details !== undefined) {
      messagesStatsAckDetails.value = []
      let samples = response.message_stats.ack_details.samples.reverse()
      for (let i = 0; i < (samples.length - 1); i++) {
        let item = samples[i]
        let nextItem = samples[i + 1]
        let obj = {
          "sample" : parseInt(nextItem.sample) - parseInt(item.sample),
          "timestamp" : item.timestamp,
        }
        messagesStatsAckDetails.value.push(obj)
      }
    }

    if(response.message_stats.confirm_details !== undefined) {
      messagesStatsConfirmDetails.value = []
      let samples = response.message_stats.confirm_details.samples.reverse()
      for (let i = 0; i < (samples.length - 1); i++) {
        let item = samples[i]
        let nextItem = samples[i + 1]
        let obj = {
          "sample" : parseInt(nextItem.sample) - parseInt(item.sample),
          "timestamp" : item.timestamp,
        }
        messagesStatsConfirmDetails.value.push(obj)
      }
    }

    initQueueTotalMessageStats(messagesStatsPublishDetails.value, messagesStatsAckDetails.value, messagesStatsConfirmDetails.value)

  })
}

function handleNodeNameList() {
  listNodeName().then(response => {
    nodeNameList.value = response
  })
}

function initQueueTotalMessage(messagesDetails, messagesReadyDetails, messagesUnacknowledgedDetails) {
  if (queueTotalMessageChartInstance == null) {
    queueTotalMessageChartInstance = echarts.init(document.getElementById('queue_total_message'))
  }
  const config = {
    title: {
      text: 'Queued messages'
    },
    legend: {},
    grid: {
      left: '5%',
      right: '1%'
    },
    tooltip: {
      formatter: function (params, ticket, callback) {
        let content = 'time: ' + moment(parseInt(params.data.timestamp)).format("yyyy-MM-DD HH:mm:ss") + '<br />'
        content = content + ' num: ' + params.data.sample
        return content
      }
    },
    dataset: [
      {
        dimensions: ['timestamp', 'sample', 'limit'],
        source: messagesDetails
      },
      {
        dimensions: ['timestamp', 'sample', 'limit'],
        source: messagesReadyDetails
      },
      {
        dimensions: ['timestamp', 'sample', 'limit'],
        source: messagesUnacknowledgedDetails
      }
    ],
    xAxis: {
      type: "category",
      axisLabel: {
        formatter: function (value, index) {
          return moment(parseInt(value)).format("yyyy-MM-DD HH:mm:ss").replace(' ', '\n')
        }
      }
    },
    yAxis: {},
    series: [
      {
        name: "Total",
        type: "line",
        datasetIndex: 0
      },
      {
        name: "Ready",
        type: "line",
        datasetIndex: 1
      },
      {
        name: "Unacked",
        type: "line",
        datasetIndex: 2
      }
    ]
  }
  queueTotalMessageChartInstance.setOption(config)
}

function initQueueTotalMessageStats(messagesStatsPublishDetails, messagesStatsAckDetails, messagesStatsConfirmDetails) {
  if (queueTotalMessageStatsChartInstance == null) {
    queueTotalMessageStatsChartInstance = echarts.init(document.getElementById('queue_total_message_stats'))
  }
  const config = {
    title: {
      text: 'Queued messages rates'
    },
    legend: {},
    grid: {
      left: '5%',
      right: '1%'
    },
    tooltip: {
      formatter: function (params, ticket, callback) {
        let content = 'time: ' + moment(parseInt(params.data.timestamp)).format("yyyy-MM-DD HH:mm:ss") + '<br />'
        content = content + ' num: ' + params.data.sample
        return content
      }
    },
    dataset: [
      {
        dimensions: ['timestamp', 'sample', 'limit'],
        source: messagesStatsPublishDetails
      },
      {
        dimensions: ['timestamp', 'sample', 'limit'],
        source: messagesStatsAckDetails
      },
      {
        dimensions: ['timestamp', 'sample', 'limit'],
        source: messagesStatsConfirmDetails
      },
    ],
    xAxis: {
      type: "category",
      axisLabel: {
        formatter: function (value, index) {
          return moment(parseInt(value)).format("yyyy-MM-DD HH:mm:ss").replace(' ', '\n')
        }
      }
    },
    yAxis: {
      min: 'dataMin'
    },
    series: [
      {
        name: "Publish",
        type: "line",
        datasetIndex: 0
      },
      {
        name: "Ack",
        type: "line",
        datasetIndex: 1
      },
      {
        name: "Confirm",
        type: "line",
        datasetIndex: 2
      }
    ]
  }
  queueTotalMessageStatsChartInstance.setOption(config)
}

function handleDate() {
  handleOverview()
}

onMounted(() => {
  handleDate()
  rabbitmqStore().setTimer(handleDate)
})

onBeforeRouteLeave(() => {
  clearInterval(rabbitmqStore().timer)
  rabbitmqStore().deleteTimer()
})

</script>

<template>
  <div style="width: 100%; height: 100%; overflow: auto">
    <el-row>
      <el-col :span="24">
        <el-card>
          <el-descriptions column="6" border>
            <el-descriptions-item v-for="(value, key) in overviewInfo.object_totals" :label="key">{{
                value
              }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
      <el-col :span="24">
        <el-card>
          <div id="queue_total_message" style="width: 100%; height: 300px">
            暂无数据
          </div>
        </el-card>
      </el-col>
      <el-col :span="24">
        <el-card>
          <div id="queue_total_message_stats" style="width: 100%; height: 300px">
            暂无数据
          </div>
        </el-card>
      </el-col>
      <el-col v-for="item in nodeNameList" :span="24">
        <el-card>
          {{ item }}
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
</style>